<script setup lang="ts">
import { onMounted } from "vue";
import * as d3 from "d3";
defineOptions({
  name: "d3-line"
});
onMounted(() => {
  initChart();
});
interface Data {
  name: string;
  value: number;
}
const data: Array<Data> = [
  { name: "星期一", value: 20 },
  { name: "星期二", value: 35 },
  { name: "星期三", value: 25 },
  { name: "星期四", value: 40 },
  { name: "星期五", value: 30 }
];
const initChart = () => {
  //指定dom来渲染图表
  const container = d3.select(".container-d3");
  //创建svg画布设定画布宽高
  const svg = container
    .append("svg")
    .classed("line-svg", true)
    .attr("height", 500)
    .attr("width", 500);
  //通过d3的api获取数组最大值
  const maxValue = d3.max(data, (d: Data) => d.value);
  //通过数据创建X轴 并设置x轴大小
  const xScale = d3
    .scaleBand()
    .domain(data.map(d => d.name))
    .range([0, 380]);
  //通过数据创建Y轴 并设置Y轴大小
  const yScale = d3.scaleLinear().domain([0, maxValue]).range([400, 0]);
  //创建一个元素 将比例尺添加上去
  svg
    .append("g")
    .attr("transform", "translate(50,420)")
    .call(d3.axisBottom(xScale));
  svg
    .append("g")
    .attr("transform", "translate(50,20)")
    .call(d3.axisLeft(yScale));
  //生成折线图的数据点
  const line = d3
    .line()
    .x(d => xScale(d.name) + xScale.bandwidth() / 2 + 50) // 设置x值
    .y(d => yScale(d.value) + 20); // 设置y值
  // 创建路径并绑定数据
  svg
    .append("path")
    .datum(data)
    .attr("fill", "none")
    .attr("stroke", "yellow") // 折线颜色
    .attr("stroke-width", 2) // 折线宽度
    .attr("d", line); // 应用线段生成器到路径
};
</script>

<template>
  <div class="container-d3" />
</template>

<style scoped>
.container-d3 {
  width: 700px;
  height: 700px;
  border: 1px solid black;
}
</style>
<style>
.line-svg {
  background-color: gray;
}
</style>
